import subprocess
import threading

from playwright.sync_api import Playwright, sync_playwright, Browser

from secware.secware import do_task


# 启动浏览器
def start_chrome(num):
    # Chrome浏览器所在路径
    chrome_path = r'"C:\Users\15319\AppData\Local\Google\Chrome\Application\chrome.exe"'
    port = 9222 + num
    # todo 关闭占用端口
    # debug 端口
    debugging_port = "--remote-debugging-port={}".format(port)
    # 用户数据
    user_data_dir = r"--user-data-dir=D:\mutiChorme\{}".format(num)
    # 代理服务器
    proxy_server = '--proxy-server=socks://127.0.0.1:7890'
    # 启动命令
    command = f"{chrome_path} {debugging_port} {user_data_dir} {proxy_server}"
    # 执行命令
    subprocess.Popen(command, shell=True)
    return port


def connect_chrome(playwright: Playwright, port) -> Browser:
    # 连接到浏览器
    return playwright.chromium.connect_over_cdp(f"http://localhost:{port}")


def main(num):
    with sync_playwright() as playwright:
        # todo 代理切换
        # 启动浏览器
        port = start_chrome(num)
        # 连接浏览器
        browser = connect_chrome(playwright, port)
        # 执行任务
        do_task(browser, num)
        # 关闭浏览器(可能会导致异步事件无法完成)
        browser.close()


if __name__ == "__main__":
    # 创建线程
    threads = []
    for i in range(5, 6):
        thread = threading.Thread(target=main, args=(i,))
        threads.append(thread)
        thread.start()

    # 等待所有线程完成
    for thread in threads:
        thread.join()
    # for i in range(1, 3):
    #     try:
    #         main(i)
    #         time.sleep(60)
    #     except Exception as e:
    #         print(f"An error occurred on iteration {i}: {e}")
